package com.woniuxy.commons.utile;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Properties;
import java.util.Random;

public class CommonsUtil {


    public static void sendMail(String target,String subject,String content) throws MessagingException {
        Properties pros = new Properties();
        pros.setProperty("mail.transport.protocol","SMTP");//设置发送邮件使用的协议
        pros.setProperty("mail.host","smtp.163.com");//设置发送邮件使用的邮件服务器
        pros.setProperty("mail.smtp.auth","true");//是否要进行验证
        Session session = Session.getInstance(pros, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //参数1：邮箱帐号
                //参数2：授权密码
                return new PasswordAuthentication("wzy1971313981@163.com","ECRBMXFEHHVLQZCI");
            }
        });
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("wzy1971313981@163.com"));//设置邮件的发送者
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(target));//设置邮件的接收者
        message.setSubject(subject);//设置邮件的标题
        message.setContent(content,"text/html;charset=utf-8");//设置邮件内容
        //发送邮件
        Transport.send(message);
    }

    public static String md5(String password) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");//根据算法名称获取加密对象
        byte[] bytes = md5.digest(password.getBytes());//执行加密操作
        return Base64.getEncoder().encodeToString(bytes);//使用base64将加密后的字节数组编码成一个字符串
    }


    public static String getActiveCode(int length){
        String source="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String activeCode="";
        for (int i = 0; i < length; i++) {
            activeCode+=source.charAt(new Random().nextInt(source.length()));
        }
        return activeCode;
    }


}
